package com.hebang.stcommunityapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

import com.hebang.stcommunityapp.activitys.MainActivity;
import com.hebang.stcommunityapp.databinding.ActivityLoginBinding;
import com.hebang.stcommunityapp.viewModel.LoginViewModel;
import qiu.niorgai.StatusBarCompat;

public class LoginActivity extends AppCompatActivity {
    private SharedPreferences sp=null;
    ActivityLoginBinding binding;
    LoginViewModel loginViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding= DataBindingUtil.setContentView(this, R.layout.activity_login);
        getSupportActionBar().hide();
        StatusBarCompat.setStatusBarColor(this, 0xff4428a3);
        loginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        loginViewModel.getLoginModel().setIsCheckPromiss(true);

        sp = this.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        String saved_username = sp.getString("USERNAME", ""); //获取sp里面存储的数据
        String saved_password = sp.getString("PASSWORD","");
        loginViewModel.getLoginModel().setUsername(saved_username);//将sp中存储的username写入EditeText
        loginViewModel.getLoginModel().setPass(saved_password);//将sp中存储的password写入EditeText
        binding.setLoginViewModel(loginViewModel);


        MutableLiveData<Boolean> nameEvent=  loginViewModel.getLoginEvent();
        nameEvent.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    if(loginViewModel.getLoginModel().isCheckPromiss()){
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("USERNAME", binding.edShoujihao.getText().toString());
                        editor.putString("PASSWORD",binding.edYanzhengma.getText().toString());
                        editor.commit();
                    }
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    Intent intent=new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    LoginActivity.this.finish();
                }else{
                    Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
}